package work.atpgroup.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import work.atpgroup.entity.ResourceLink;
import work.atpgroup.entity.User;
import work.atpgroup.entity.tool.ApplicationProperties;
import work.atpgroup.service.ResourceService;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Controller
public class ResourceUploadController {
    @Resource(name="resourceService")
    private ResourceService resourceService;
    @PostMapping("/resourceUpload/static-file")
    public String upload(@RequestParam("file") MultipartFile file, Model model, HttpServletRequest request) throws IOException, ServletException {
        User user = (User) request.getSession().getAttribute("user");
        System.out.println(user);
        if(user==null){
            model.addAttribute("uploadErrorMessage","你还没有登录，请先登录再上传文件吧");
            return "public/error/uploadError";
        }

        String fileName = file.getOriginalFilename();
        String storage_Name = user.getUserId()+"-"+fileName;
        ResourceLink resourceInDB = resourceService.getResourceLinkByPath(storage_Name);
        if(resourceInDB!=null){
            model.addAttribute("uploadErrorMessage","已经有该命名的文件了，请尝试其他名字");
            return "public/error/uploadError";
        }
        ResourceLink resourceLink = new ResourceLink();
        resourceLink.setUserId(user.getUserId());
        resourceLink.setNotThumbnail(true);
        resourceLink.setPath(storage_Name);
        resourceLink.setDate(new Date());
        resourceService.insertResourceLink(resourceLink);
        resourceLink.setResourceId(resourceService.getResourceLinkIdByPath(storage_Name));

        String absoluteLocalPath = ApplicationProperties.getAbsoluteLocalPath(storage_Name);
        String prePath = absoluteLocalPath.substring(0,absoluteLocalPath.lastIndexOf(File.separator));
        if(!new File(prePath).exists()){
            boolean success = new File(prePath).mkdirs();
            if(!success){
                return "public/error/uploadError";
            }
        }
        try {
            file.transferTo(new File(absoluteLocalPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("uploadSuccessMessage","上传文件"+fileName+"成功");
        model.addAttribute("latest-upload-file","resources/"+resourceLink.getResourceId());
        return "redirect:/admin/static-file-list";
    }
}
